package com.cloudpivot.receivales.contract.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.contract.domain.NormalReturn;
import com.cloudpivot.receivales.contract.domain.oa.OAContract;
import com.cloudpivot.receivales.contract.service.OAService;
import com.cloudpivot.receivales.contract.util.GetDocumentUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.File;

@Slf4j
@Service
public class OASreviceImpl implements OAService {
    @Value("${ZDE6.url}")
    private String url;

    @Value("${ZDE6.username}")
    private String username;

    @Value("${ZDE6.password}")
    private String password;

    @Value("${ZDE6.fullPath}")
    private String fullPath;

    @Override
    public NormalReturn getOAPOJO(OAContract oaContract) {
        return null;
    }

    @Override
    public void pushContract(JSONObject contractinfo) {
        String recFolderId = "627";
        String ticket = getToken();
        String suffix = "/api/v2/record/create.html";
        String recordData = contractinfo.toJSONString();

        // 构建初始请求（推送记录数据）
        MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                .addTextBody("ticket", ticket)
                .addTextBody("recFolderId", recFolderId)
                .addTextBody("recordData", recordData, ContentType.create("text/plain", Consts.UTF_8));
        String recordId = pushResult(builder, suffix).getString("ID");
        String recordIdAndTable = recordId + ",行政管理类";
        String[] ids = contractinfo.getString("附件").split(",");

        for (String id : ids) {
            // 获取文件并构建文件上传请求
            File file = new GetDocumentUtil().getDocfile(Integer.parseInt(id));
            suffix = "/api/v2/document/uploadDoc.html";
            String route = fullPath+contractinfo.getString("申请日期").substring(0,4)+"/"+ file.getName();

            MultipartEntityBuilder buildercontract = MultipartEntityBuilder.create()
                    .addTextBody("ticket", ticket)
                    .addTextBody("fullPath", route, ContentType.create("text/plain", Consts.UTF_8))
                    .addTextBody("recordIdAndTable", recordIdAndTable, ContentType.create("text/plain", Consts.UTF_8))
                    .addBinaryBody("docUpload", file, ContentType.APPLICATION_OCTET_STREAM, file.getName())
                    .addTextBody("mode", "both");

            // 执行文件上传
            pushResult(buildercontract, suffix);
            // 文件上传成功后删除文件
            if (file.exists()) {
                file.delete();
            }
        }

    }

    public JSONObject pushResult(MultipartEntityBuilder builder, String suffix) {
        String urlString = url + suffix;
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost con = new HttpPost(urlString);
            con.setEntity(builder.build());
            try (CloseableHttpResponse response = client.execute(con)) {
                int statusCode = response.getStatusLine().getStatusCode();
                log.info("响应状态码: " + statusCode);
                String resultStr = EntityUtils.toString(response.getEntity());
                log.info("返回结果：" + resultStr);
                return JSONObject.parseObject(resultStr);
            }
        } catch (Exception e) {
            log.error("请求失败: ", e);
            return null;
        }
    }

    public static String generateRecFolderId(int baseYear, int baseId, int inputYear) {
        int recFolderId = baseId + (inputYear - baseYear);
        return String.valueOf(recFolderId);
    }


    /**
     * 获取文档系统token
     * @return 返回令牌
     */
    private String getToken() {
        String token = null;
        try {
            // 构造请求 URL
            String requestUrl = String.format("%s?username=%s&password=%s&validMin=%d", url+"/ssoGetTicket.html", username, password, 30);

            // 创建 HTTP 客户端并发送 GET 请求
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpGet httpGet = new HttpGet(requestUrl);
                // 执行请求并获取响应
                token = EntityUtils.toString(httpClient.execute(httpGet).getEntity());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

}
